package com.huluobo.a2203kotlinjetpackdemo.paging

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.a2203kotlinjetpackdemo.R
import com.huluobo.a2203kotlinjetpackdemo.databinding.ItemBinding

/**
 *  Created by LC on 2024/7/22.
 *  paging数据源的适配器
 */
class PagingAdapter : PagingDataAdapter<Bean, PagingAdapter.ViewHolder>(COMPARATOR) {

    companion object {
        private val COMPARATOR = object : DiffUtil.ItemCallback<Bean>() {
            override fun areItemsTheSame(oldItem: Bean, newItem: Bean): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: Bean, newItem: Bean): Boolean {
                return oldItem == newItem
            }
        }
    }

    //viewHolder,主要负责把layout传递给外部
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val binding: ItemBinding? = DataBindingUtil.bind(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding?.bean = getItem(position)//给每一个item中的DataBinding的Bean赋值
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
        return ViewHolder(view)
    }
}